Challenge 1

The full text of this chapter, to read or revisit. To practise, do the exercises.

▶ Do the exercises

Exercise 1 — Safe Stats Viewer - Get Stat Safely

Start building a safe stats viewer! - Create get_stat(codemon, stat_name) that uses try/except to handle KeyError - If stat exists: return the value - If stat doesn't exist: print "[stat_name] not found!" and return 0 - Test by getting existing stats (attack) and non-existing stats (speed)

Starter code
# Create get_stat function with KeyError handling aquachu = {"name": "Aquachu", "hp": 100, "attack": 50, "defense": 30} # Test it

Exercise 2 — Safe Stats Viewer - Calculate Total

Expand your stats viewer to calculate totals: - Create calculate_total_stats(codemon) that safely sums all stat values (exclude "name") - Test by calculating the total stats of a Codémon

Starter code
def get_stat(codemon, stat_name): try: return codemon[stat_name] except KeyError: print(f"{stat_name} not found!") return 0 # Create calculate_total_stats function aquachu = {"name": "Aquachu", "hp": 100, "attack": 50, "defense": 30} # Test it

Exercise 3 — Safe Stats Viewer - Stats Average

Complete your stats viewer with average calculation: - Create get_stat_average(codemon, stat_list) that uses try/except to handle ZeroDivisionError - Calculate the average of requested stats - Return 0 if stat_list is empty - Test with a normal list and an empty list

Starter code
def get_stat(codemon, stat_name): try: return codemon[stat_name] except KeyError: print(f"{stat_name} not found!") return 0 # Create get_stat_average function with ZeroDivisionError handling aquachu = {"name": "Aquachu", "hp": 100, "attack": 50, "defense": 30} # Test it
Back to the course